<template>
  <div class="app-container">
    <div class="filter-container">
      <el-date-picker
        v-model="querySchedulesByUserParams.date"
        type="date"
        size="medium"
        value-format="yyyy-MM-dd"
        placeholder="起始时间"/>
      <el-radio-group v-model="scheduleType" size="medium" style="margin-left: 20px" @change="radioChange">
        <el-radio :label="1" border>日程</el-radio>
        <el-radio :label="2" border>会议</el-radio>
        <el-radio :label="3" border>考勤</el-radio>
      </el-radio-group>
      <span class="filter-container-right">
        <router-link :to="{ name: 'MaintainAttention' }">
          <el-button type="primary" size="medium" icon="el-icon-plus">维护我的关注</el-button>
        </router-link>
      </span>

    </div>
    <el-container :style="{ height: schduleHeight + 'px' }">
      <el-scrollbar style="height: 100%">
        <el-aside width="180px" class="container-aside">
          <p style="text-align: center;color: #409EFF;height: 15px;">我的关注</p>
          <el-collapse v-model="activeNames" @change="handleChange">
            <el-collapse-item name="1">
              <template slot="title">
                <span class="group-title">用户</span>
              </template>
              <p
                v-for="user in concerns.userConcerns"
                :key="user.id"
                :class="{'item-active': activeId === user.id}"
                class="group-item"
                @click="getUserScheduleType(user)"
              >{{ user.real_name }}</p>
            </el-collapse-item>
            <el-collapse-item v-if="!isAdmin" name="2">
              <template slot="title">
                <span class="group-title">自定义组</span>
              </template>
              <p
                v-for="group in concerns.personalUserGroupConcerns"
                :key="group.id"
                :class="{'item-active': activeId === group.id}"
                class="group-item"
                @click="getUserGroupScheduleType(group)"
              >{{ group.group_name }}</p>
            </el-collapse-item>
            <el-collapse-item name="3">
              <template slot="title">
                <span class="group-title">全局组</span>
              </template>
              <p
                v-for="group in concerns.CommonUserGroupConcerns"
                :class="{'item-active': activeId === group.id}"
                :key="group.id"
                class="group-item"
                @click="getUserGroupScheduleType(group)"
              >{{ group.group_name }}</p>
            </el-collapse-item>
            <el-collapse-item name="4">
              <template slot="title">
                <span class="group-title">部门</span>
              </template>
              <p
                v-for="dept in concerns.deptConcerns"
                :class="{'item-active': activeId === dept.department}"
                :key="dept.department"
                class="group-item"
                @click="getDeptScheduleType(dept)"
              >{{ dept.department }}</p>
            </el-collapse-item>
          </el-collapse>
        </el-aside>
      </el-scrollbar>
      <el-main style="height: 100%">
        <el-scrollbar style="height: 100%">
          <el-table
            v-loading="listLoading"
            :data="userSchedule"
            border
            fit
            highlight-current-row
            style="width: 100%">
            <el-table-column align="center" width="40">
              <template slot-scope="scope">
                <span>{{ isGroup ? scope.row.real_name : scope.row.time }}</span>
              </template>
            </el-table-column>
            <el-table-column v-for="day in days" :key="day.day" :label="day.day + ' ' +day.week" align="center">
              <template slot-scope="scope">
                <span
                  v-for="(sch, index) in scope.row[day.property]"
                  :key="sch.id"
                  :class="index !== scope.row[day.property].length - 1 ? 'schedule-item' :'schedule-item-end'"
                  @click="showSchedule(sch)">
                  <!--<div>{{ sch.title }}</div>
                <div>{{ sch.start_date }}</div>
                <div>{{ sch.address }}</div>-->
                  <div>{{ sch.title }}  {{ sch.start_date }}  {{ sch.address }}</div>
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-scrollbar>
      </el-main>
    </el-container>
    <el-dialog :visible.sync="scheduleVisible" :title="scheduleType === 1 ? '日程详情' : '考勤详情'" width="500px">
      <div class="scheule-detail">
        <p>标题：{{ scheduleDetail.title }}</p>
        <p>地址：{{ scheduleDetail.address }}</p>
        <p>开始时间：{{ scheduleDetail.start_date }}</p>
        <p>结束时间：{{ scheduleDetail.closed_date }}</p>
        <p v-if="scheduleType === 1">时间节点：
          <el-radio v-model="scheduleDetail.is_full_day" :label="0" disabled>全天</el-radio>
          <el-radio v-model="scheduleDetail.is_full_day" :label="1" disabled>上午</el-radio>
          <el-radio v-model="scheduleDetail.is_full_day" :label="2" disabled>下午</el-radio>
        </p>
        <p v-if="scheduleType === 1" style="display: flex">
          <span style="display: inline-block; width: 150px;">参与者：</span>
          <span>
            <el-tag v-for="item in scheduleDetail.users" :key="item.id" type="primary" class="user-tag">
              {{ item.realName }}
            </el-tag>
          </span>
        </p>
        <p>描述：{{ scheduleDetail.description }}</p>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="meetingVisible" title="会议详情" width="500px">
      <div class="scheule-detail">
        <p>会议名称：{{ meetingDetail.meeting_name }}</p>
        <p>会议房间：{{ meetingDetail.meetingroom_name }}</p>
        <p>会议日期：{{ meetingDetail.meeting_date }}</p>
        <p>会议时间：{{ meetingDetail.meeting_time }}</p>
        <p style="display: flex">
          <span style="display: inline-block; width: 150px;">参与者：</span>
          <span>
            <el-tag v-for="item in meetingDetail.inter" :key="item.id" type="primary" class="user-tag">
              {{ item.meeting_inter_name }}
            </el-tag>
          </span>
        </p>
        <p>会议分类：{{ meetingDetail.meeting_category }}</p>
        <p>会议形式：{{ meetingDetail.meeting_format }}</p>
        <p>会议联系人：{{ meetingDetail.meeting_contactor_name }}</p>
        <p>会议电话：{{ meetingDetail.meeting_contactor_phone }}</p>
        <p>会议单位：{{ meetingDetail.meeting_contactor_unit }}</p>
        <p>创建日期：{{ meetingDetail.create_date }}</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import commonApi from '@/api/commonApi'
import { parseTime } from '@/utils/index'
import { mapGetters } from 'vuex'
export default {
  name: 'MyAttention',
  data() {
    return {
      listLoading: false,
      activeId: 1,
      concerns: {
        userConcerns: [],
        personalUserGroupConcerns: [],
        CommonUserGroupConcerns: [],
        deptConcerns: []
      },
      activeNames: ['1', '2', '3', '4'],
      userSchedule: [],
      userGroupSchedule: [],
      days: [],
      scheduleVisible: false,
      meetingVisible: false,
      scheduleDetail: {},
      meetingDetail: {},
      querySchedulesByUserParams: { date: parseTime(new Date(), '{y}-{m}-{d}') },
      queryByUserGroupParams: {},
      scheduleYear: '',
      scheduleType: 1,
      isGroup: false,
      schduleHeight: null,
      tempObjData: {} // 最近点击对象信息
    }
  },
  computed: {
    ...mapGetters(['isAdmin'])
  },
  created() {
    this.getMyGroup()
    this.getConcern()
    this.getCurrentUserSchedule()
    this.tempObjData = this.$store.getters.user
    this.activeId = this.tempObjData.id
  },
  methods: {
    // radio日程类型转化
    radioChange() {
      if (this.tempObjData.department) { // 根据临时对象判断是否 是部门
        this.getDeptScheduleType()
      } else if (this.tempObjData.group_name) { // 根据临时对象判断是否 是用户组
        this.getUserGroupScheduleType()
      } else {
        this.getUserScheduleType() // 默认是用户
      }
    },

    // 部门 日程、会议、考勤 选择展示
    getDeptScheduleType(dept = this.tempObjData) {
      this.tempObjData = dept
      this.isGroup = true
      if (!this.querySchedulesByUserParams.date) {
        this.querySchedulesByUserParams.date = parseTime(new Date(), '{y}-{m}-{d}')
      }
      this.userSchedule = []
      if (this.scheduleType === 1) {
        this.getDeptSchedule(dept)
      } else if (this.scheduleType === 2) {
        this.getDetpMeeting(dept)
      } else if (this.scheduleType === 3) {
        this.getDeptLeave(dept)
      }
    },
    // 部门一周日程
    getDeptSchedule(dept) {
      this.activeId = dept.department
      this.queryByUserGroupParams.department = dept.department
      this.queryByUserGroupParams.date = this.querySchedulesByUserParams.date
      this.listLoading = true
      commonApi('/schedule/queryByDepartment', 'post', this.queryByUserGroupParams).then(response => {
        if (response.code === 1) {
          this.initDays(this.querySchedulesByUserParams.date) // 必须在数据转化前
          this.userGroupScheduleTransform(response.data)
          this.listLoading = false
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },
    // 部门一周会议
    getDetpMeeting(dept) {
      this.activeId = dept.department
      this.queryByUserGroupParams.department = dept.department
      this.queryByUserGroupParams.date = this.querySchedulesByUserParams.date
      this.listLoading = true
      commonApi('/meeting/queryByDepartment', 'post', this.queryByUserGroupParams).then(response => {
        if (response.code === 1) {
          this.initDays(this.querySchedulesByUserParams.date) // 必须在数据转化前
          for (const obj of response.data) { // 将数据格式转为日程格式 再调用用户组数据转化
            obj.schedules = this.meetingKeyTransform(obj.meetingList)
            delete (obj.meetingList)
          }
          this.userGroupScheduleTransform(response.data)
          this.listLoading = false
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },
    // 部门一周考勤
    getDeptLeave(dept) {
      this.activeId = dept.department
      this.queryByUserGroupParams.department = dept.department
      this.queryByUserGroupParams.date = this.querySchedulesByUserParams.date
      this.listLoading = true
      commonApi('/schedule/queryLeaveByDepartment', 'post', this.queryByUserGroupParams).then(response => {
        if (response.code === 1) {
          this.listLoading = false
          this.initDays(this.querySchedulesByUserParams.date) // 必须在数据转化前
          for (const obj of response.data) {
            obj.schedules = []
            for (const leave of obj.leaveList) {
              obj.schedules.push(this.keyToLowerCase(leave))
            }
            delete (obj.leaveList)
          }
          this.userGroupScheduleTransform(response.data)
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },

    // 用户组 日程、会议、考勤 选择展示
    getUserGroupScheduleType(userGroup = this.tempObjData) {
      this.tempObjData = userGroup
      this.isGroup = true
      if (!this.querySchedulesByUserParams.date) {
        this.querySchedulesByUserParams.date = parseTime(new Date(), '{y}-{m}-{d}')
      }
      this.userSchedule = []
      if (this.scheduleType === 1) {
        this.getUserGoupSchedule(userGroup)
      } else if (this.scheduleType === 2) {
        this.getUserGroupMeeting(userGroup)
      } else if (this.scheduleType === 3) {
        this.getUserGroupLeave(userGroup)
      }
    },
    // 用户组一周日程
    getUserGoupSchedule(userGroup) {
      this.listLoading = true
      this.activeId = userGroup.id
      this.queryByUserGroupParams.group_id = userGroup.id
      this.queryByUserGroupParams.date = this.querySchedulesByUserParams.date
      commonApi('/schedule/queryByUserGroup', 'post', this.queryByUserGroupParams).then(response => {
        if (response.code === 1) {
          this.initDays(this.querySchedulesByUserParams.date) // 必须在数据转化前
          this.userGroupScheduleTransform(response.data)
          this.listLoading = false
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },
    // 用户组一周会议
    getUserGroupMeeting(userGroup) {
      this.activeId = userGroup.id
      this.queryByUserGroupParams.group_id = userGroup.id
      this.queryByUserGroupParams.date = this.querySchedulesByUserParams.date
      this.listLoading = true
      commonApi('/meeting/queryByGroup', 'post', this.queryByUserGroupParams).then(response => {
        if (response.code === 1) {
          this.initDays(this.querySchedulesByUserParams.date) // 必须在数据转化前
          for (const obj of response.data) { // 将数据格式转为日程格式 再调用用户组日程格式数据转化
            obj.schedules = this.meetingKeyTransform(obj.meetingList)
            delete (obj.meetingList)
          }
          this.userGroupScheduleTransform(response.data)
          this.listLoading = false
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },
    // 用户组一周考勤
    getUserGroupLeave(userGroup) {
      this.activeId = userGroup.id
      this.queryByUserGroupParams.group_id = userGroup.id
      this.queryByUserGroupParams.date = this.querySchedulesByUserParams.date
      this.listLoading = true
      commonApi('/schedule/queryLeaveByGroup', 'post', this.queryByUserGroupParams).then(response => {
        if (response.code === 1) {
          this.listLoading = false
          this.initDays(this.querySchedulesByUserParams.date) // 必须在数据转化前
          for (const obj of response.data) {
            obj.schedules = []
            for (const leave of obj.leaveList) {
              obj.schedules.push(this.keyToLowerCase(leave))
            }
            delete (obj.leaveList)
          }
          this.userGroupScheduleTransform(response.data)
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },
    // 用户组 数据转化
    userGroupScheduleTransform(tempRes = []) {
      if (tempRes.length === 0) return
      for (let j = 0; j < tempRes.length; j++) {
        for (let z = 0; z < tempRes[j].schedules.length; z++) {
          for (let i = 0; i < this.days.length; i++) {
            if (!tempRes[j][this.days[i].property]) {
              tempRes[j][this.days[i].property] = []
            }
            if (this.days[i].property === (tempRes[j].schedules[z].start_date).substr(0, 10)) {
              tempRes[j][this.days[i].property].push(tempRes[j].schedules[z])
            }
          }
        }
      }
      this.userSchedule = tempRes
    },

    // 日程详情展示
    showSchedule(schedule) {
      if (this.scheduleType === 1) {
        this.scheduleVisible = true
        commonApi(`/schedule/details/${schedule.id}`, 'get').then(response => {
          if (response.code === 1) {
            this.scheduleDetail = response.data
          }
        })
      } else if (this.scheduleType === 2) {
        this.meetingVisible = true
        commonApi(`/meeting/details/${schedule.id}`, 'get').then(response => {
          if (response.code === 1) {
            this.meetingDetail = response.data
          }
        })
      } else if (this.scheduleType === 3) {
        this.scheduleVisible = true
        this.scheduleDetail = schedule
      }
    },
    // 初始化一周七天
    initDays(date = parseTime(new Date(), '{y}-{m}-{d}')) {
      this.days = []
      const newDate = new Date(date)
      let currentWeek = newDate.getDay()
      this.scheduleYear = parseTime(newDate, '{y}')
      if (currentWeek === 0) {
        currentWeek = 7
      }
      // 初始日期
      for (let i = 1; i < 8; i++) {
        const d = new Date(date)
        d.setDate(d.getDate() + (i - currentWeek))
        let week
        switch (d.getDay()) {
          case 0:
            week = '周日'
            break
          case 1:
            week = '周一'
            break
          case 2:
            week = '周二'
            break
          case 3:
            week = '周三'
            break
          case 4:
            week = '周四'
            break
          case 5:
            week = '周五'
            break
          case 6:
            week = '周六'
            break
        }
        const dayobject = {} // 用一个对象包装Date对象  以便为以后预定功能添加属性
        dayobject.property = parseTime(d, '{y}-{m}-{d}')
        dayobject.day = parseTime(d, '{m}/{d}')
        dayobject.week = week
        this.days.push(dayobject)// 将日期放入data 中的days数组 供页面渲染使用
      }
    },
    // 自定义组数据
    getMyGroup() {
      commonApi('/userGroup/queryMyGroup', 'get').then(response => {
        if (response.code === 1) {
          this.concerns.personalUserGroupConcerns = response.data
        }
      })
    },
    // 已关注
    getConcern() {
      this.listLoading = true
      commonApi('/userGroup/queryConcern', 'get').then(response => {
        this.concerns.userConcerns = [this.$store.getters.user, ...response.data.userConcerns]
        this.concerns.CommonUserGroupConcerns = response.data.userGroupConcerns
        this.concerns.deptConcerns = response.data.deptConcerns
        this.listLoading = false
      })
    },
    // 当前用户一周日程
    getCurrentUserSchedule() {
      this.listLoading = true
      this.schduleHeight = document.body.clientHeight - 160
      commonApi('/schedule/mySchedule', 'post', { date: this.querySchedulesByUserParams.date }).then(response => {
        if (response.code === 1) {
          this.initDays(this.querySchedulesByUserParams.date)
          this.userScheduleTransform(response.data.schedules)
          this.listLoading = false
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },

    // 用户日程、会议、考勤 选择展示
    getUserScheduleType(user = this.tempObjData) {
      this.tempObjData = user
      this.isGroup = false
      if (!this.querySchedulesByUserParams.date) {
        this.querySchedulesByUserParams.date = parseTime(new Date(), '{y}-{m}-{d}')
      }
      this.userSchedule = []
      if (this.scheduleType === 1) {
        this.getUserSchedule(user)
      } else if (this.scheduleType === 2) {
        this.getUserMeeting(user)
      } else if (this.scheduleType === 3) {
        this.getUserLeave(user)
      }
    },
    // 用户一周日程
    getUserSchedule(user) {
      this.activeId = user.id
      this.querySchedulesByUserParams.username = user.username
      this.listLoading = true
      commonApi('/schedule/querySchedulesByUser', 'post', this.querySchedulesByUserParams).then(response => {
        if (response.code === 1) {
          this.initDays(this.querySchedulesByUserParams.date) // 必须在数据转化前
          this.userScheduleTransform(response.data)
          this.listLoading = false
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },
    //  用户一周会议
    getUserMeeting(user) {
      this.activeId = user.id
      this.querySchedulesByUserParams.real_name = user.real_name
      this.listLoading = true
      commonApi('/meeting/query', 'post', this.querySchedulesByUserParams).then(response => {
        if (response.code === 1) {
          this.listLoading = false
          this.initDays(this.querySchedulesByUserParams.date) // 必须在数据转化前
          this.userScheduleTransform(this.meetingKeyTransform(response.data))
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },
    // 会议字段转化 为日程相关字段
    meetingKeyTransform(dataTemp = []) {
      const tempArr = []
      for (let i = 0; i < dataTemp.length; i++) { // 字段转化
        const tempObj = {}
        tempObj.id = dataTemp[i].id
        tempObj.title = dataTemp[i].meeting_name
        tempObj.start_date = dataTemp[i].meeting_date + ' ' + dataTemp[i].meeting_time
        tempObj.address = dataTemp[i].meetingroom_name
        if (parseFloat(dataTemp[i].meeting_time.substr(0, 2)) < 12) {
          tempObj.is_full_day = 1
        } else {
          tempObj.is_full_day = 2
        }
        tempArr.push(tempObj)
      }
      return tempArr
    },
    // 用户一周考勤
    getUserLeave(user) {
      this.activeId = user.id
      this.querySchedulesByUserParams.username = user.username
      this.listLoading = true
      commonApi('/schedule/queryLeaveByUser', 'post', this.querySchedulesByUserParams).then(response => {
        if (response.code === 1) {
          this.listLoading = false
          this.initDays(this.querySchedulesByUserParams.date) // 必须在数据转化前
          const tempArr = []
          for (const obj of response.data) {
            tempArr.push(this.keyToLowerCase(obj))
          }
          this.userScheduleTransform(tempArr)
        }
      }).catch(() => {
        this.initDays(this.querySchedulesByUserParams.date)
      })
    },
    // 用户维度返回数据转化
    userScheduleTransform(data) {
      const tempRes = data
      if (tempRes.length === 0) return
      const tempSchAm = { time: '上 午' } // 上午
      const tempSchPm = { time: '下 午' } // 下午
      for (let i = 0; i < this.days.length; i++) {
        tempSchPm[this.days[i].property] = []
        tempSchAm[this.days[i].property] = []
        for (let j = 0; j < tempRes.length; j++) {
          if (this.days[i].property === (tempRes[j].start_date).substr(0, 10)) {
            if (tempRes[j].is_full_day === 2) {
              tempSchPm[this.days[i].property].push(tempRes[j])
            } else {
              tempSchAm[this.days[i].property].push(tempRes[j])
            }
          }
        }
      }
      this.userSchedule = [tempSchAm, tempSchPm]
    },
    // 考勤 key 大写转小写
    keyToLowerCase(jsonObj) {
      for (const key in jsonObj) {
        if (key === 'START_DATE' || key === 'CLOSED_DATE') { // 日期转化
          jsonObj[key] = parseTime(new Date(jsonObj[key]), '{y}-{m}-{d}')
        }
        jsonObj[key.toLowerCase()] = jsonObj[key]
        delete (jsonObj[key])
      }
      return jsonObj
    },
    // 侧栏收合状态改变触发
    handleChange(val) {
      console.log(val)
    }
  }
}
</script>

<style scoped lang="scss">
  .scheule-detail{
    font-size: 15px;
    margin: -30px 30px -10px;
  }
  .user-tag{
    margin: 0 10px 10px 0;
  }
 .schedule-top{
   background-color: white;
   margin-bottom: 10px;
 }
  .group-title{
    margin-left: 20px;
  }
 .group-item{
   margin-left: 40px;
   cursor: pointer;
   overflow: hidden;
   text-overflow: ellipsis;
   white-space: nowrap;
   width: 130px;
   &:hover{
     color: #409EFF;
   }
 }
  .item-active{
    color: #409EFF;
  }
  .schedule-item{
    display: block;
    padding: 10px 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.09);
    &:hover{
      cursor: pointer;
      box-shadow: 5px 5px 5px #d3dce6;
      border-color: #d3dce6;
    }
  }
 .schedule-item-end {
   display: block;
   margin: 10px 0;
   &:hover{
     cursor: pointer;
     box-shadow: 5px 5px 5px #d3dce6;
     border-color: #d3dce6;
   }
 }
  .container-aside{
    background-color: white;
    margin-right: 10px;
    overflow-x: hidden;
  }
  .el-scrollbar__wrap {
    overflow-x: hidden !important;
  }
</style>
